package com.cqyc.shop.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqyc.shop.comm.Pager;
import com.cqyc.shop.comm.commException;
import com.cqyc.shop.domain.Cart;
import com.cqyc.shop.domain.User;
import com.cqyc.shop.services.CartServices;

@WebServlet(urlPatterns="/joincart.do")
public class JoinShowCartServlet extends HttpServlet{
	private static final long serialVersionUID = -4964085433418242953L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private CartServices cartServices = new CartServices();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("显示购物车商品表演开始");
		try {
			//1:从前台获取参数
			
			String pageSize = request.getParameter("pageSize");
			String currentPage = request.getParameter("currentPage"); 
			
			HttpSession session = request.getSession();
			Object ouser = session.getAttribute("user");
			User user =  (User)ouser;
			logger.debug("{}",user.getUsercode());
		
			Cart cart = new Cart();
			cart.setUsercode(user.getUsercode());
			Pager pager = new Pager();
			

				if(pageSize==null || pageSize.length()<1) {
					pager.setPageSize(3);
				}else {
					pager.setPageSize(Integer.valueOf(pageSize));
					logger.debug("{}",pager.getPageSize());
				}
				if(currentPage==null || currentPage.length() < 1) {
					pager.setCurrentPage(1);
				}else {
					pager.setCurrentPage(Integer.valueOf(currentPage));
					logger.debug("{}",pager.getCurrentPage());
				}
			//2:数据转换
			//3:数据校验
			if(user.getUsercode()==null) {
				throw new commException("没有登录无法访问购物车哟");
			}
			//4:业务处理
			List<Cart> carts = cartServices.findPager(cart,pager);
			request.setAttribute("carts", carts);
			request.setAttribute("pager", pager);
			//5:跳转
			request.getRequestDispatcher("/showCart.jsp").forward(request, response);
		} catch (Exception e) {
			logger.debug("{}",e.getMessage());
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/showCart.jsp").forward(request, response);
		}
	}
	
}
